package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.guide

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import android.widget.ScrollView
import com.anythink.core.api.ATAdInfo
import com.anythink.interstitial.api.ATInterstitial
import com.anythink.nativead.api.ATNativeAdView
import com.anythink.nativead.api.ATNativePrepareExInfo
import com.anythink.nativead.api.ATNativePrepareInfo
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.BuildConfig
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.listener.manual_load.TopOnInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.SelfRenderViewUtil
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.SplashType
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.TopOnSplashFinishObservable
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.TopOnSplashFinishObserver
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseActivity
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_gender.BpGenderActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_main.BpMainActivity
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.DoubleClickListener
import com.bp.hearthealth.pulse.lnapps.bp_utils.SpUtils
import com.bp.hearthealth.pulse.lnapps.databinding.ActivityGuideSplashBinding
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import me.jessyan.autosize.internal.CustomAdapt


@SuppressLint("CustomSplashScreen")
class GuideSplashActivity : BpBaseActivity<ActivityGuideSplashBinding>(), CustomAdapt,
    TopOnSplashFinishObserver {

    private var firstOpen: Boolean = true
    private var adInterLaunchIntro: Boolean = true
    private var nativeAd: NativeAd? = null
    private var topOnNativeAd: com.anythink.nativead.api.NativeAd? = null

    override fun initData() {
        super.initData()
        //界面展示
        adInterLaunchIntro = AdsSwitch.getBoolean(AdsSwitch.adInterLaunchIntro)
        if (!AdsSwitch.getBoolean(AdsSwitch.adInterCacheControl) && adInterLaunchIntro) {
            TopOnInterAdManager.manualLoadAd()
        }
        AppsFlyerUtils.trackEvent("intro_show")
        //此处使用设置语言IS_SET_LANGUAGE字段，仅做引导页只显示一次判断
        SpUtils.saveString(Constants.IS_SET_LANGUAGE, Constants.IS_SET_LANGUAGE)
        firstOpen = intent.getBooleanExtra("isFirstOpen", false)
//        loadNativeAd()
        loadTopOnNativeAd()
        binding.banner.setAdapter(object : BannerImageAdapter<Int>(DataBean.getImageList()) {
            override fun onBindView(
                holder: BannerImageHolder, data: Int, position: Int, size: Int
            ) {
                holder.imageView.setImageResource(data)
            }
        }).addBannerLifecycleObserver(this).setIndicator(CircleIndicator(this))
    }

    override fun initListener() {
        super.initListener()
        //跳过
        binding.tvSkip.setOnClickListener(object : DoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
//                loadAdMobInsertAd()
                loadTopOnInsertAd()
            }
        })
        //Let go
        binding.tvLetGo.setOnClickListener(object : DoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
//                loadAdMobInsertAd()
                loadTopOnInsertAd()
            }
        })
    }


    override fun onPause() {
        if (topOnNativeAd != null) {
            topOnNativeAd!!.onPause()
        }
        super.onPause()
    }

    override fun onResume() {
        if (topOnNativeAd != null) {
            topOnNativeAd!!.onResume()
        }
        super.onResume()
    }


    private fun loadTopOnNativeAd() {
        if (TopOnNativeAdManager.getNativeAds().isNotEmpty()) {
            setNativeTopOnAdView()
        } else {
            TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
                override fun onNativeAdLoaded() {
                    LogUtil.iTopOn("TopOn 【原生广告】 监听，显示广告")
                    if (TopOnNativeAdManager.getNativeAds().isNotEmpty()) {
                        setNativeTopOnAdView()
                    }
                }
            })
        }
    }

    private fun setNativeTopOnAdView() {
        topOnNativeAd = TopOnNativeAdManager.getNativeAds().first()
        TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
            override fun onAdImpressed(view: ATNativeAdView, entity: ATAdInfo) {
                AppsFlyerUtils.trackEvent("ad_native_intro_show")
                ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID,"f664720236fa99")
                TopOnNativeAdManager.removeUsedNativeAdListener()
            }
        })
        binding.nativeAdView.removeAllViews()
        var mNativePrepareInfo: ATNativePrepareInfo? = null
        try {
            mNativePrepareInfo = ATNativePrepareExInfo()
            if (topOnNativeAd?.isNativeExpress == true) {
                LogUtil.iTopOn("【原生广告】 自渲染广告")
                topOnNativeAd?.renderAdContainer(
                    binding.nativeAdView,
                    null
                )
            } else {
                LogUtil.iTopOn("【原生广告】 模板广告")
                SelfRenderViewUtil.bindSelfRenderView(
                    activity,
                    topOnNativeAd?.adMaterial,
                    binding.nativeSelfrenderView.root,
                    mNativePrepareInfo
                )
                topOnNativeAd?.renderAdContainer(
                    binding.nativeAdView,
                    binding.nativeSelfrenderView.root
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        topOnNativeAd?.prepare(binding.nativeAdView, mNativePrepareInfo)
        binding.nativeAdView.visibility = View.VISIBLE
        TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
            override fun onAdCloseButtonClick(view: ATNativeAdView, entity: ATAdInfo) {
                TopOnNativeAdManager.destroyAd()
                binding.nativeAdView.visibility = View.GONE
            }
        })
        binding.scrollView.fullScroll(ScrollView.FOCUS_DOWN)
    }


    private fun loadTopOnInsertAd() {
        topOnNativeAd?.let { TopOnNativeAdManager.removeUsedNativeAd(it) }
//        if (BuildConfig.DEBUG) {
//            adInterLaunchIntro = true
//        }
        if (adInterLaunchIntro) {
            if (TopOnInterAdManager.isAdReady()) {
                TopOnInterAdManager.setManualLoadListener(object : TopOnInterstitialAdListener {
                    override fun onFireBaseAdIsClosed() {
                        startBpActivity()
                    }

                    override fun onInterstitialAdClose(entity: ATAdInfo) {
                        startBpActivity()
                    }

                    override fun onInterstitialAdShow(entity: ATAdInfo) {

                    }
                })
                TopOnInterAdManager.showInterstitialAd(this)
            } else {
                startBpActivity()
            }
        } else {
            startBpActivity()
        }
    }

    private fun loadAdMobInsertAd() {
        if (AdsSwitch.getBoolean(AdsSwitch.adInterLaunchIntro)) {
            AdMobInterstitialAdManager.setInterstitialAdListener(object :
                AdMobInterstitialAdListener {
                override fun onAdDismissedFullScreenContent() {
                    startBpActivity()
                }

                override fun onNotReady() {
                    startBpActivity()
                }

                override fun onAdFailedToShowFullScreenContent() {
                    startBpActivity()
                }

                override fun onAdShowedFullScreenContent() {
                    //埋点

                }
            })
            AdMobInterstitialAdManager.showInterstitialAd(this)
        } else {
            startBpActivity()
        }
    }

    private fun startBpActivity() {
        if (firstOpen && AdsSwitch.getBoolean(AdsSwitch.pageLaunchGender)) {
            TopOnInterAdManager.setManualLoadListener(null)
            startActivity(Intent(BpApplication.context, BpGenderActivity::class.java))
        } else {
            TopOnSplashFinishObservable.notifySplash(SplashType.TYPE_LAUNCH_FINISH)
            startActivity(Intent(BpApplication.context, BpMainActivity::class.java))
        }
        finish()
    }

    /**
     * 加载原生广告
     *     ■ 原生广告资源加载到，展示广告
     *     ■ 原生广告资源未加载到，隐藏广告位
     */
    private fun loadNativeAd() {
        AdMobNativeAdManager.setNativeAdListener(object : AdMobNativeAdListener {
            override fun onAdLoaded(loadedNativeAd: MutableList<NativeAd>) {
                setNativeAdView(loadedNativeAd)
            }

            override fun onAdImpression() {
                //原生广告埋点
                AppsFlyerUtils.trackEvent("ad_native_intro_show")
                ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID,"f664720236fa99")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【Intro页_原生广告】")
                AdMobNativeAdManager.removeUsedNativeAdListener()
            }
        })
        val nativeAdList = AdMobNativeAdManager.getNativeAds()
        if (nativeAdList.isNotEmpty()) {
            setNativeAdView(nativeAdList)
        }
    }

    private fun setNativeAdView(nativeAdList: MutableList<NativeAd>) {
        nativeAd = nativeAdList.first()
        binding.nativeAdContainer.setNativeAd(nativeAd)
        binding.nativeAdContainer.visibility = View.VISIBLE
    }

    override fun isBaseOnWidth(): Boolean {
        return false
    }

    override fun getSizeInDp(): Float {
        return 812f
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        ImmersionBar.with(this).titleBar(binding.toolbar).init()
    }

    override fun onDestroy() {
        super.onDestroy()
        TopOnInterAdManager.releaseManualLoadInterstitialAd()
        TopOnSplashFinishObservable.unRegisterSplash(this)
    }

    override fun topOnSplashFinish(splashType: SplashType) {
        if (splashType == SplashType.TYPE_LAUNCH_FINISH) {
            LogUtil.iTopOn("销毁引导页")
            finish()
        }
    }
}